﻿using Serilog.Core;
using Serilog.Events;
using System;
using System.Drawing;
using System.Windows.Forms;

namespace ybx_caller
{
    public class RichTextBoxSink : ILogEventSink, IDisposable
    {
        private readonly IFormatProvider _formatProvider;
        private readonly RichTextBox _richTextBox;

        public RichTextBoxSink(RichTextBox richTextBox, IFormatProvider formatProvider)
        {
            _richTextBox = richTextBox ?? throw new ArgumentNullException(nameof(richTextBox));
            _formatProvider = formatProvider;
        }

        public void Emit(LogEvent logEvent)
        {
            if (logEvent == null) return;
            var renderedMessage = logEvent.RenderMessage(_formatProvider);
            var formattedMessage = logEvent.Timestamp.ToString("yyyy-MM-dd HH:mm:ss.fff") + " [" +
                                   logEvent.Level.ToString().ToUpper().Substring(0, 3) + "] " +
                                   renderedMessage + Environment.NewLine +
                                   (logEvent.Exception != null ? logEvent.Exception.ToString() + Environment.NewLine : "");

            Color textColor = Color.White; // 默认白色
            switch (logEvent.Level)
            {
                case LogEventLevel.Warning:
                    textColor = Color.DarkOrange; // 警告黄色
                    break;
                case LogEventLevel.Error:
                case LogEventLevel.Fatal:
                    textColor = Color.Red; // 错误和致命错误红色
                    break;
            }

            if (_richTextBox.InvokeRequired)
            {
                _richTextBox.Invoke(new Action(() =>
                {
                    AppendText(_richTextBox, formattedMessage, textColor);
                }));
            }
            else
            {
                AppendText(_richTextBox, formattedMessage, textColor);
            }
        }

        private void AppendText(RichTextBox box, string text, Color color)
        {
            box.SelectionStart = box.TextLength;
            box.SelectionLength = 0;
            box.SelectionColor = color;
            box.AppendText(text);
            box.SelectionColor = box.ForeColor;
        }

        public void Dispose()
        {
            // 清理资源
        }
    }
}
